<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <!-- <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24"> </a-row>
      </a-form>
    </div> -->
    <!-- 查询区域-END -->
    <!-- 顶部搜索区：用 form 包裹，行内布局 -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <form class="search-bar" @submit.prevent="handleSearch">
        <a-input-search
          v-model="keyword"
          placeholder="请输入关键字"
          style="width: 320px"
          enter-button
          @search="handleSearch"
        />
        <a-button type="primary" html-type="submit" style="margin-left: 8px;margin-right:8px">
          搜索
        </a-button>
        <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      </form>

      <!-- <a-button type="primary" icon="download" @click="handleExportXls('测试用例表')">导出</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query
        :fieldList="superFieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->

    <!-- 下部分：左侧树 + 右侧内容 -->
    <a-row class="bottom-box" type="flex">
      <!-- 左侧树（窄） -->
      <a-col class="left-pane">
        <!-- 右键菜单 -->
        <a-menu
          v-show="menuVisible"
          :style="{ position: 'fixed', zIndex: 9999, ...menuStyle }"
          @click="handleMenuClick"
        >
          <a-menu-item key="edit">编辑</a-menu-item>
          <a-menu-item key="delete">删除</a-menu-item>
        </a-menu>

        <a-directory-tree
          :tree-data="treeData"
          :replace-fields="replaceFields"
          @select="onTreeSelect"
          @rightClick="onRightClick"
          default-expand-all
        />
      </a-col>

      <!-- 右侧中心区域（宽） -->
      <a-col class="right-pane">
        <!-- 顶部：当前节点信息（保留） -->
        <a-card size="small" style="margin-bottom:12px">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="名称">
              {{ activeNode.caseName || '—' }}
            </a-descriptions-item>
            <a-descriptions-item label="简述">
              {{ activeNode.caseVersion || '—' }}
            </a-descriptions-item>
            <a-descriptions-item label="项目类型">
              {{ activeNode.purpose || '—' }}
            </a-descriptions-item>
            <a-descriptions-item label="ID">
              {{ activeNode.id || '—' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 下方：文件模式 / 列表模式 二选一 -->
        <a-card v-if="showFile" title="模板文件" size="small">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item label="Python 文件">
              <a :href="activeNode.filePy" target="_blank">{{ activeNode.filePy || '—' }}</a>
            </a-descriptions-item>
            <a-descriptions-item label="YAML 文件">
              <a :href="activeNode.fileYml" target="_blank">{{ activeNode.fileYml || '—' }}</a>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card v-else title="模板列表" size="small">
          <a-list v-if="displayList.length" :data-source="displayList" item-layout="horizontal">
            <a-list-item slot="renderItem" slot-scope="item">
              <a-list-item-meta
                :title="item.caseName"
                :description="`简述：${item.caseVersion || '—'} | 项目类型：${item.purpose || '—'}`"
              />
            </a-list-item>
          </a-list>
          <a-empty v-else description="暂无数据" />
        </a-card>
      </a-col>
      <!-- <a-col class="right-pane">
        <a-card title="模板详情" size="small">
          <a-list v-if="displayList.length" :data-source="displayList" item-layout="horizontal">
            <a-list-item slot="renderItem" slot-scope="item">
              <a-list-item-meta :title="item.title" :description="item.caseVersion" />
            </a-list-item>
          </a-list>
          <a-empty v-else description="暂无数据" />
        </a-card>
      </a-col> -->
    </a-row>

    <test-user-case-modal ref="modalForm" @ok="modalFormOk"></test-user-case-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import TestUserCaseModal from './modules/TestUserCaseModal'
import { getAction, deleteAction } from '@/api/manage'

export default {
  name: 'TestUserCaseList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    TestUserCaseModal
  },
  data() {
    return {
      description: '测试用例表管理页面',
      keyword: '',
      selectedKey: null,
      activeNode: {}, // 右侧头部回显信息
      replaceFields: { children: 'children', title: 'caseName', key: 'id' },
      /* 三级树数据 */
      treeData: [],
      url: {
        list: '/testUserCase/queryAllCase',
        delete: '/testUserCase/delete',
        deleteBatch: '/testUserCase/deleteBatch',
        exportXlsUrl: '/testUserCase/exportXls',
        importExcelUrl: '/testUserCase/importExcel',
        getList: '/testUserCase/queryAllCase'
      },
      dictOptions: {},
      superFieldList: [],
      menuVisible: false,
      menuStyle: { left: 0, top: 0 },
      rightNode: null // 当前右键节点
    }
  },
  created() {
    this.loadData()
  },
  computed: {
    /* 新增：当前节点是否展示文件 */
    showFile() {
      return this.activeNode && this.activeNode.purpose === 2
    },
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    /* 右侧展示列表：搜索优先，树选中其次 */
    displayList() {
      const list = this.flattenTemplates(this.treeData)
      if (this.keyword) {
        const kw = this.keyword.toLowerCase()
        return list.filter(t => t.caseName.toLowerCase().includes(kw) || t.caseVersion.toLowerCase().includes(kw))
      }
      if (this.selectedKey) {
        const node = this.findNode(this.treeData, this.selectedKey)
        if (!node) return []
        return node.children ? this.flattenTemplates(node.children) : [node]
      }
      return []
    }
  },
  methods: {
    loadData() {
      getAction(this.url.list, {}).then(res => {
        if (res.success) {
          this.treeData = res.result
          console.log(res, 'res')
        } else {
          console.error('getDictItems error: : ', res)
          this.dictOptions = []
        }
      })
    },
    /* 搜索触发 */
    handleSearch() {
      this.selectedKey = null
      this.activeNode = {} // 搜索时顶部不展示单节点
    },
    /* 树选择 */
    onTreeSelect(keys) {
      this.keyword = ''
      const node = this.findNode(this.treeData, keys[0])
      this.activeNode = node || {}
      this.selectedKey = keys[0] || null
    },
    /* 工具：拍平所有模板节点 */
    flattenTemplates(nodes) {
      let res = []
      nodes.forEach(n => {
        if (n.purpose !== 0) res.push(n)
        if (n.children && n.children.length) {
          res = res.concat(this.flattenTemplates(n.children))
        }
      })
      return res
    },
    /* 工具：根据 key 查找任意节点 */
    findNode(nodes, key) {
      console.log(nodes, 'nodes')
      for (const n of nodes) {
        if (n.id == key) return n
        if (n.children) {
          const found = this.findNode(n.children, key)
          if (found) return found
        }
      }
      return null
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'caseName', text: '用例名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'caseVersion', text: '用例版本', dictCode: '' })
      fieldList.push({ type: 'string', value: 'purpose', text: '测试目的', dictCode: '' })
      this.superFieldList = fieldList
    },
    /* ================= 右键 ================= */
    onRightClick(e) {
      const { event, node } = e
      // 根节点(pid===0)不弹菜单
      console.log(node.dataRef, 'node.dataRef')
      if (node.dataRef.pid == 0) return
      event.preventDefault()
      this.rightNode = node.dataRef
      this.menuStyle = { left: `${event.clientX}px`, top: `${event.clientY}px` }
      this.menuVisible = true
      // 点页面任意处关闭
      const close = () => {
        this.menuVisible = false
        document.removeEventListener('click', close)
      }
      this.$nextTick(() => document.addEventListener('click', close))
    },

    handleMenuClick({ key }) {
      if (key === 'delete') this.deleteNode(this.rightNode)
      if (key === 'copy') this.copyNode(this.rightNode)
      if (key === 'edit') this.editNode(this.rightNode)
      this.menuVisible = false
    },

    /* ================= 删除 ================= */
    deleteNode(target) {
      // const parent = this.findParent(this.treeData, target.id)
      // // if (!parent) return
      // const idx = parent.children.findIndex(c => c.id === target.id)
      // parent.children.splice(idx, 1)
      let that = this
      deleteAction(that.url.delete, { id: target.id }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          // 若当前右侧展示的是该分支，刷新
          this.refreshDisplay()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    editNode(target) {
      this.handleEdit(target)
    },
    /* ================= 复制 ================= */
    copyNode(target) {
      const parent = this.findParent(this.treeData, target.id)
      if (!parent) return
      const clone = {
        ...target,
        id: Date.now(), // 简易唯一 key
        caseName: target.caseName + '_副本',
        children: target.children ? target.children.map(this.deepClone) : undefined
      }
      parent.children.push(clone)
      this.$message.success('已复制')
      this.refreshDisplay()
    },

    findParent(nodes, id) {
      for (const n of nodes) {
        if (n.children && n.children.some(c => c.id === id)) return n
        if (n.children) {
          const p = this.findParent(n.children, id)
          if (p) return p
        }
      }
      return null
    },
    deepClone(node) {
      const c = { ...node, id: Date.now() + Math.random() }
      if (node.children) c.children = node.children.map(this.deepClone)
      return c
    },
    refreshDisplay() {
      // 触发 computed 重新计算
      this.loadData()
      this.keyword = this.keyword.trim()
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.right-pane .ant-descriptions-item-label {
  width: 80px;
  text-align: right;
}
/* 下部分：左右分栏，占剩余高度 */
.bottom-box {
  flex: 1;
  overflow: hidden;
}

/* 左侧树：窄 */
.left-pane {
  width: 260px;
  border-right: 1px solid #eee;
  overflow-y: auto;
  padding: 12px;
}

/* 右侧中心区域：宽 */
.right-pane {
  flex: 1;
  overflow-y: auto;
  padding: 12px 24px;
}
.ant-menu {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
